package com.sgb.kjwl.view.ui.activity.self;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddressAddBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.UserAddressEntity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.self.AddressAddModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 *
 */
public class AddressAddActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    @Inject
    AddressAddModel viewModel;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
//    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private boolean isLoaded = false;
    private ActivityAddressAddBinding binding;
    private String id;
    private String mAreaCode;
    private UserAddressEntity mData;
    private boolean isNewAddress;

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, AddressAddActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent)
                .selfModule(new SelfModule(this)).build().inject(this);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(AddressAddActivity.this, R.layout.activity_address_add);
        binding.itemLocate.setOnWholeItemClickListener(this);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.rightView.setVisibility(View.GONE);
        binding.include.rightView.setText("保存");
        binding.include.rightView.setOnClickListener(this);
        binding.itemPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemZip.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itvCName.setNoSymbol();
        binding.tvCommit.setOnClickListener(this);
        binding.tvDelete.setOnClickListener(this);
    }

    @Override
    protected void init() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        id = getIntent().getStringExtra("id");
        isNewAddress = TextUtils.isEmpty(id);
        if (isNewAddress) {
            binding.include.titleView.setText("新增地址");
            binding.tvDelete.setVisibility(View.GONE);
        } else {
            binding.include.titleView.setText("编辑地址");
            binding.tvDelete.setVisibility(View.VISIBLE);
            viewModel.getIdAddress(id);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_commit:
                if (TextUtils.isEmpty(binding.itvCName.getContent())) {
                    MToast.showToast(AddressAddActivity.this, "请填写企业名称");
                    return;
                } else if (TextUtils.isEmpty(binding.itemName.getContent())) {
                    MToast.showToast(AddressAddActivity.this, "请填写姓名");
                    return;
                } else if (!CheckUtils.isMobileNum(binding.itemPhone.getContent())) {
                    MToast.showToast(AddressAddActivity.this, "请填写正确的手机号");
                    return;
                } else if (TextUtils.isEmpty(binding.itemLocate.getContent())) {
                    MToast.showToast(AddressAddActivity.this, "请选择所在区域");
                    return;
                } else if (TextUtils.isEmpty(binding.etDetail.getText())) {
                    MToast.showToast(AddressAddActivity.this, "请填写详细地址");
                    return;
                }
                UserAddressEntity data = new UserAddressEntity();
                data.setName(binding.itemName.getContent());
                data.setPhone(binding.itemPhone.getContent());
                data.setDistrictNo(mAreaCode);
                data.setDetail(binding.etDetail.getText().toString());
                data.setDefaultAdress(binding.switchDefault.isChecked());
                data.setId(id);
                data.setCompanyName(binding.itvCName.getContent());
                data.setPostalCode(binding.itemZip.getContent());

                if (!isNewAddress) {
                    data.setId(id);
                    viewModel.userAddressEntity.set(data);
                    viewModel.overrideAddress();
                } else {
                    viewModel.userAddressEntity.set(data);
                    viewModel.commitAddress();
                }
                break;
            case R.id.tv_delete:
                showDialog(viewModel.userAddressEntity.get().getId());
                break;
        }
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    private void showCityPop() {
        CityPickView cityOption = new CityPickBuilder(AddressAddActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    mAreaCode = opt3.get(options1).get(options2).get(options3).getNo();
                    cityPosition3 = options3;
                    viewModel.userAddressEntity.get().setDistrictName(areaName);
                    viewModel.userAddressEntity.get().setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
                }
                String content = addressEntityList.get(options1).getName() + opt2.get(options1).get(options2).getName() + areaName;
                binding.itemLocate.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;
                viewModel.userAddressEntity.get().setProvinceName(addressEntityList.get(options1).getName());
                viewModel.userAddressEntity.get().setProvinceNo(addressEntityList.get(options1).getId());
                viewModel.userAddressEntity.get().setCityName(opt2.get(options1).get(options2).getName());
                viewModel.userAddressEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
            }
        }).setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_locate:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {

        for (int i = 0; i < addressEntityList.size(); i++) {

            if (!isNewAddress) {
                if (addressEntityList.get(i).getId().equals(mData.getProvinceNo())) {
                    cityPosition1 = i;
                }
            }

//            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {

                if (!isNewAddress) {
                    if (addressEntityList.get(i).getChildren().get(j).getId().equals(mData.getCityNo())) {
                        cityPosition2 = j;
                    }
                }

//                cityList.add(addressEntityList.get(i).getChildren().get(j));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                    if (!isNewAddress) {
                        for (int k = 0; k < children.size(); k++) {
                            if (children.get(k).getId().equals(mData.getDistrictNo())) {
                                cityPosition3 = k;
                            }
                        }
                    }
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public void showAddress(UserAddressEntity data) {
        this.mData = data;
        mAreaCode = data.getDistrictNo();
        viewModel.userAddressEntity.set(data);
        binding.itemName.setContent(data.getName());
        binding.itemPhone.setContent(data.getPhone());
        binding.etDetail.setText(data.getDetail());
        binding.itemLocate.setContent(data.getProvinceName() + data.getCityName() + data.getDistrictName());
        binding.switchDefault.setChecked(data.isDefaultAdress());
        binding.itvCName.setContent(data.getCompanyName());
        binding.itemZip.setContent(data.getPostalCode());
    }

    private void showDialog(String id) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("删除地址");
        tv_title.setVisibility(View.VISIBLE);
        tv_message.setText("确定要删除地址吗");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求接口
//                deletePerson.put("id", id);
                viewModel.delIdAddress(id);
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setTextColor(getResources().getColor(R.color.color_tab_one));
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }
}
